
// Base64 编码
function base64Encode(str) {
    let base64 = '';
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    
    for (let i = 0; i < str.length; i += 3) {
      const char1 = str.charCodeAt(i);
      const char2 = str.charCodeAt(i + 1);
      const char3 = str.charCodeAt(i + 2);
  
      const enc1 = char1 >> 2;
      const enc2 = ((char1 & 3) << 4) | (char2 >> 4);
      const enc3 = ((char2 & 15) << 2) | (char3 >> 6);
      const enc4 = char3 & 63;
  
      if (i + 1 >= str.length) {
        base64 += chars.charAt(enc1) + chars.charAt(enc2) + '==';
      } else if (i + 2 >= str.length) {
        base64 += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + '=';
      } else {
        base64 += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4);
      }
    }
    return base64;
  }
  
  // Base64 解码
  function base64Decode(base64) {
    let str = '';
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  
    let i = 0;
    while (i < base64.length) {
      const enc1 = chars.indexOf(base64.charAt(i++));
      const enc2 = chars.indexOf(base64.charAt(i++));
      const enc3 = chars.indexOf(base64.charAt(i++));
      const enc4 = chars.indexOf(base64.charAt(i++));
  
      const char1 = (enc1 << 2) | (enc2 >> 4);
      const char2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      const char3 = ((enc3 & 3) << 6) | enc4;
  
      str += String.fromCharCode(char1);
  
      if (enc3 !== 64) {
        str += String.fromCharCode(char2);
      }
      if (enc4 !== 64) {
        str += String.fromCharCode(char3);
      }
    }
    return str;
  }
  

/* 暴露函数 */
module.exports ={
    base64Encode,
    base64Decode,
}
 